AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( 'shared.lua' )
util.PrecacheSound("npc/roller/mine/combine_mine_deploy1.wav")
util.PrecacheSound("npc/roller/mine/combine_mine_active_loop1.wav")

function ENT:SpawnFunction( ply, tr )
	if ( !tr.Hit ) then return end
	--local SpawnPos = tr.HitPos + tr.HitNormal * 16
	local SpawnPos = tr.HitPos + Vector(0,0,100)
	local ent = ents.Create("sent_combine_mine")
	ent:SetPos(SpawnPos)
	ent:Spawn()
	ent:Activate()
	ent:Arm()
	return ent
end
function ENT:Initialize()
	self.Entity:SetModel("models/props_combine/combine_mine01.mdl")
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
	self.Entity:SetSolid( SOLID_VPHYSICS )
	local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
		phys:SetMass(1)
	end
	self.exploding = false
	self.Range = 150
	self.Armed = false
end

function ENT:Arm()
	self.Armed = true
	local phys = self.Entity:GetPhysicsObject()
end

function ENT:Think()
	if not self.Armed then return end
	local trace = util.QuickTrace(self.Entity:GetPos(),self.Entity:GetPos()+(self.Entity:GetUp()*-10), self.Entity)
	if trace.HitWorld then
		local cPos = self.Entity:GetPos()
		local startPos = cPos + Vector(self.Range,self.Range,self.Range)
		local endPos = cPos - Vector(self.Range,self.Range,0)
		local rng = ents.FindInBox( endPos, startPos ) --I hate find in box
		for k,v in pairs(rng) do
			if( (v:IsPlayer() or v:IsNPC() or v:IsVehicle()) and not self.exploding) then
				local phys = self.Entity:GetPhysicsObject()
				if (phys:IsValid()) then
					cPos = cPos + Vector(0,0,5)
					self.Entity:SetPos(cPos)
					phys:EnableGravity(true)
					phys:ApplyForceCenter( Vector(0,0,8000))
					self.Entity:EmitSound("npc/roller/mine/combine_mine_deploy1.wav", 150,125)
					self.exploding = true
					local explo=ents.Create("env_explosion")
					explo:SetPos(cPos)
					explo:SetParent(self.Entity)
					explo:SetOwner(self.Entity:GetOwner())
					explo:SetKeyValue("iMagnitude","240");
					explo:SetKeyValue("iRadiusOverride", 240)
					explo:Spawn()
					explo:Activate()
					explo:Fire("explode", "", 1)
					explo:Fire("kill","",1)
					self.Entity:StopSound("npc/roller/mine/combine_mine_deploy1.wav")
					self.Entity:StopSound("npc/roller/mine/combine_mine_deploy1.wav")
					self.Entity:StopSound("npc/roller/mine/combine_mine_deploy1.wav")
					self.Entity:Fire("kill", "", "1")
				end
			end
		end
	end
end